﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System;
using UtfprLibrary.EntityFramework.Exceptions;

namespace UtfprLibrary.EntityFramework.Helpers {
    public static class EntityCollectionHelper {
        /// <summary>
        /// Get the EntityCollection type properties of an entity
        /// </summary>
        /// <param name="entity">the entity object to be investigated.</param>
        /// <returns>a List of EntityCollection type properties</returns>
        public static List<PropertyInfo> GetEntityCollectionProperties(object entity) {
            try {
                var entityCollectionProperties = entity
                    .GetType()
                    .GetProperties()
                    .Where(p => p.PropertyType.Name == "EntityCollection`1")
                    .ToList();

                return entityCollectionProperties;
            } catch (Exception ex) {
                throw new UtfprEFHelpersException("", ex);
            }
        }

        /// <summary>
        /// Get the entity collection property value of an entity
        /// </summary>
        /// <param name="entity">the entity with values</param>
        /// <param name="entityCollectionProperty">the entity collection property to be investigated</param>
        /// <returns>the value of a entity property</returns>
        public static object GetEntityCollection(object entity, PropertyInfo entityCollectionProperty) {
            try {
                return entityCollectionProperty.GetValue(entity, null);
            } catch (Exception ex) {
                throw new UtfprEFHelpersException("", ex);
            }
        }

        /// <summary>
        /// Get a List of entity collection property values from an entity
        /// </summary>
        /// <param name="entity">the entity with collection values</param>
        /// <returns>a List of entity collection values</returns>
        public static List<object> GetEntityCollections(object entity) {
            try {
                var entityCollections = new List<object>();

                foreach (var entityCollectionProperty in EntityCollectionHelper.GetEntityCollectionProperties(entity)) {
                    entityCollections.Add(GetEntityCollection(entity, entityCollectionProperty));
                }

                return entityCollections;
            } catch (Exception ex) {
                throw new UtfprEFHelpersException("", ex);
            }
        }
    }
}
